<template>
  <div class='shopping-car-page'>
    <div class="shopping-car-state">
      <span @click="changeState">{{state === '0'? '编辑': '完成'}}</span>
    </div>
    <div v-for="(item,index) in merchantList" class="merchant-item" :key="index">
      <div class="merchant-item-name">
        <div class="check-image-view" v-if="!item.checked" @click="changeMerchantCheck(index)"></div>
        <img class="check-image" v-if="item.checked" src="../assets/checked.png" @click="changeMerchantCheck(index)"/>
        <img class="merchant-image" src="../assets/xian-img.png"/>
        <span>{{item.shopName}}</span>
      </div>
      <div class="goods-item" v-for="(item1,index1) in item.productList" :key="index1" @click="gotoGoodsInfo(item1)">
        <div class="checked-goods-image-view" v-if="!item1.checked" @click="changeGoodsCheck(item1,index)"></div>
        <img class="checked-goods-image" v-if="item1.checked" src="../assets/checked.png" @click="changeGoodsCheck(item1,index)">
        <img class="goods-image" :src="item1.picUrl"/>
        <div class="goods-font">
          <div style="height: 3.2rem">
            <div class="goods-name" v-if="item1.propertiesName.length !== 0">{{item1.productName}}</div>
            <div class="goods-norms" v-if="item1.propertiesName !== null && item1.propertiesName.length !== 0 && item1.propertiesName !== ''">{{item1.propertiesName}}</div>
            <div style="height: 1.173rem" v-if="!(item1.propertiesName !== null && item1.propertiesName.length !== 0 && item1.propertiesName !== '')"></div>
            <div style="height: 1.173rem"></div>
          </div>
          <div class="goods-font-bottom">
            <div class="goods-fee">
              <span class="icon">￥</span>
              {{item1.productPrice}}
            </div>
            <div class="goods-num-view">
              <div class="goods-num-sub" @click="subNum(item1)" >-</div>
              <div class="goods-num">{{item1.productNumber}}</div>
              <div class="goods-num-add" @click="addNum(item1)" >+</div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div style="height: 2.667rem"></div>
    <div class="shopping-car-bottom" v-if="state === '0'">
      <div class="sum-fee">
        <div class="fee" v-if="state === '0'">合计<div class="fee-num">￥{{sumFee}}</div></div>
        <div class="font" v-if="state === '0'">(不含运费)</div>
      </div>
      <div :class="['submit', state === '1'?'color-red':'']" @click="submit">{{state === '0'?'去结算': '删除'}}</div>
    </div>
    <div class="shopping-car-bottom" v-if="state === '1'">
      <div class="checked-goods-image-view-color" v-if="!checked" @click="changeAll"></div>
      <img class="checked-goods-image" v-if="checked" src="../assets/checked.png" @click="changeAll"/>
      <span>全选</span>
      <div class="sum-fee"></div>
      <div :class="['submit', state === '1'?'color-red':'']" @click="submit">{{state === '0'?'去结算': '删除'}}</div>
    </div>
  </div>
</template>
<script>
import { API } from '../config'
  export default {
    name:'shoppingcar',
    data() {
      return {
        state: '0',  // 0 完成状态   1 编辑状态
        merchantList: [],
        checked: false
      }
    },
    computed: {
      sumFee () {
        var fee = 0.00
        if (this.merchantList.size === 0) {
          return fee
        } else {
          this.merchantList.forEach(item => {
            item.productList.forEach(s => {
              if (s.checked) {
                fee = parseFloat(s.productPrice) * s.productNumber + fee
              }
            })
          })
        }
        return fee.toFixed(2)
      }
    },
    methods:{
      gotoGoodsInfo (item1) {
        let productId = item1.productId
        let vm = this
        vm.$router.push('/goods/detail?id=' + productId)
      },
      changeState: function () {
        let vm = this
        vm.state = vm.state === '0' ? '1' : '0'
        vm.checked = false
        vm.merchantList.forEach(item => {
          item.checked = false
          if (item.productList.size !== 0) {
            item.productList.forEach(s => {
              s.checked = false
            })
          }
        })
      },
      changeMerchantCheck (index) {
        let vm = this
        var flag = !vm.merchantList[index].checked
        var canChange = true
        if (flag) {
          // 改成商户选中状态
          vm.merchantList.forEach(item => {
            if (item.checked) {
              canChange = false
            } else {
              item.productList.forEach(s => {
                if (s.checked) {
                  canChange = false
                }
              })
            }
          })
        }
        if (canChange) {
          vm.merchantList[index].checked = flag
          vm.merchantList[index].productList.forEach(item => {
            item.checked = flag
          })
        }
        /*
        vue实现双向数据绑定的机制是数据劫持，也就是在所有对象上有个Object.defineProperty()方法，通过监听set，get方法去实现，而数组没有这两个方法，所以就不会更新view
        所以通过手动的方式更新
        */
        vm.$set(vm.merchantList,index,vm.merchantList[index]) 
      },
      changeGoodsCheck (item1,index) {
        let vm = this
        var flag = true
        var shopId = ''
        var shoppingCartId = item1.shoppingCartId
        vm.merchantList.forEach(item => {
          item.productList.forEach(s => {
            if (s.shoppingCartId === shoppingCartId) {
              flag = s.checked
              shopId = item.shopId
              if (s.checked) {
                s.checked = !s.checked
              }
            }
          })
        })
        if (!flag) {
          var canChange = true
          vm.merchantList.forEach(item => {
            if (item.shopId !== shopId) {
              item.productList.forEach(s => {
                if (s.checked) {
                  canChange = false
                }
              })
            }
          })
          if (canChange) {
            vm.merchantList.forEach(item => {
              if (item.shopId === shopId) {
                item.productList.forEach(s => {
                  if (s.shoppingCartId === shoppingCartId) {
                    s.checked = !s.checked
                  }
                })
              }
            })
          }
        }
        var flagOne = true  
        vm.merchantList.forEach(item => {
          if (shopId === item.shopId) {
            item.productList.forEach(a => {
              if (!a.checked) {
                flagOne = false
              }
            })
            item.checked = flagOne
          }
        })
        vm.$set(vm.merchantList,index,vm.merchantList[index]) 
        event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
      },
      changeAll () {
        let vm = this
        if (vm.state !== '0') {
          vm.checked = !vm.checked
          vm.merchantList.forEach(item => {
            item.checked = vm.checked
            item.productList.forEach(s => {
              s.checked = vm.checked
            })
          })
        }
      },
      submit () {
        let vm = this
        if (vm.state === '0') {
          var ids = ''
          vm.merchantList.forEach(item => {
            item.productList.forEach(s => {
              if (s.checked) {
                if (ids.length === 0) {
                  ids = s.shoppingCartId
                } else {
                  ids = ids + ',' + s.shoppingCartId
                }
              }
            })
          })
          if (ids !== '') {
            vm.$router.push({
              path: '/order/order?shoppingCarIds=' + ids
            })
          }
        } else {
          var idList = []
          this.merchantList.forEach(item => {
            item.productList.forEach(s => {
              if (s.checked) {
                idList.push(parseInt(s.shoppingCartId))
              }
            })
          })
          // 调用删除购物车接口 /shoppingcart/delete

          let vm = this
          let accesstoken = vm.getLocalStorage('accesstoken')
          vm.$axios.post(API + '/shoppingcart/delete?',{shoppingCartIds:idList},{
            headers: {'accesstoken': accesstoken}//设置header信息
          }).then((response) => {
            if (response.data.code === 200) {
              for (var i = 0; i < this.merchantList.length; i++) {
                this.merchantList[i].productList = this.merchantList[i].productList.filter(s => s.productNumber > 0 && !s.checked)
              }
              this.merchantList = this.merchantList.filter(s => s.productList.length > 0 && !s.checked)
            }
          })
        }
      },
      subNum (item1) {
        let vm = this
        let shoppingCartId = item1.shoppingCartId
        var productNumber = 0
        var ids = []
        vm.merchantList.forEach(item => {
          item.productList.forEach(s => {
            productNumber = item1.productNumber
            if (item.productNumber === 1) {
              ids.push(s.shoppingCartId)
            }
          })
        })
        if (productNumber <= 1) {
          event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
          return
        }
        let accesstoken = vm.getLocalStorage('accesstoken')
        if(productNumber > 1){
          vm.$axios.post(API + '/shoppingcart/addproductnum',{shoppingCartId:shoppingCartId,productNum:-1},{
            headers: {'accesstoken': accesstoken}//设置header信息
          }).then((res) => {
            vm.resDeal(res.data,shoppingCartId)
          })
        }else{
          vm.$axios.post(API + '/suyuan_mall/shoppingcart/delete',{shoppingCartIds:ids},{
            headers: {'accesstoken': accesstoken}//设置header信息
          }).then((res) => {
            vm.resDeal(res.data,shoppingCartId)
          })
        }
        event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
      },
      resDeal(res,shoppingCartId){
        let vm = this
        if (res.code === 200) {
          vm.merchantList.forEach(item => {
            item.productList.forEach(s => {
              if (s.shoppingCartId === shoppingCartId && s.productNumber >= 1) {
                s.productNumber--
              }
            })
          })
        for (var i = 0; i < vm.merchantList.length; i++) {
          vm.merchantList[i].productList = vm.merchantList[i].productList.filter(s => s.productNumber > 0)
        }
        vm.merchantList = vm.merchantList.filter(s => s.productList.length > 0)
        }
        event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
      },
      addNum (item1) {
        let vm = this
        let accesstoken = vm.getLocalStorage('accesstoken')
        let shoppingCartId = item1.shoppingCartId
        vm.$axios.post(API + '/shoppingcart/addproductnum',{shoppingCartId:shoppingCartId,productNum:1},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((response) => {
          if (response.data.code === 200) {
            vm.merchantList.forEach(item => {
              item.productList.forEach(s => {
                if (s.shoppingCartId === shoppingCartId) {
                  s.productNumber++
                }
              })
            })
          }
        })
        event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
      },
      getInfo() {
        let vm = this
        let accesstoken = vm.getLocalStorage('accesstoken')
        // vm.$message(accesstoken)
        vm.$axios.get(API + '/shoppingcart/getList',{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((response) => {
          if (response.data.code === 200) {
            vm.merchantList = response.data.data
            vm.merchantList.forEach(item => {
              item.checked = false
              item.productList.forEach(s => {
                s.productPrice = parseFloat(s.productPrice / 100) + ''
                s.checked = false
              })
            })
            // console.log(vm.merchantList)
          } else {
            vm.$message(response.data.msg)
          }
        })
      }
    },
    mounted() {
      let vm = this;
      vm.getInfo();
    }
  }
</script>

<style lang='less' scoped>
  @import '../css/common.less';
  @import '../css/shoppingCar.less';
</style>
